<template>
  <div class="my-order">
    <van-search
        class="order-header"
        autocomplete="off"
        show-action
        placeholder="请输入订单关键词"
        v-model="form.searchCtt"
        @search="handleSearch()"
    >
      <template #left>
        <van-icon class="left-icon" name="arrow-left" @click="$router.replace('/my')"/>
      </template>
      <template #action>
        <van-icon class="right-icon" name="ellipsis"/>
      </template>
    </van-search>
    <div class="filter-line">
      <template v-for="item in filterConfigItems" :key="item.key">
        <span
            :class="item.key === form.status && 'active'"
            @click="handleFilterItemClick(item.key)">
          {{ item.label }}
        </span>
      </template>
    </div>
    <div class="order-list">
      <ZJScrollView ref="orderListScrollRef" :wrapperConfig="orderListScrollConfig">
        <template #content>
          <p class="pull-down-text">{{ pullDownText }}</p>
          <template v-if="orderModule.orderList.length === 0">
            <van-empty description="暂无订单"/>
          </template>
          <template v-else>
            <div v-for="item in orderModule.orderList" :key="item.id" class="list-item card-normal"
                 @click="handleListItemClick(item.orderNo)">
              <div class="item-title">
                <p class="name">乐享家私自营店</p>
                <p class="status">{{ statusList[item.status] }}</p>
              </div>
              <template v-for="jItem in item.sysOrderItemsVo">
                <div class="item-detail">
                  <div class="detail-img">
                    <img :src="jItem.productImage" alt="goods_img">
                  </div>
                  <div class="detail-info">
                    <p class="goods-name">{{ jItem.productName }}</p>
                    <p class="goods-spec">{{ Object.values(jItem.productSpecs).join(" ") }}</p>
                  </div>
                  <div class="detail-price">
                    <p class="price">
                      <span>￥</span>
                      <span>{{ jItem.currentUnitPrice * jItem.quantity }}</span>
                    </p>
                    <p class="count">×{{ jItem.quantity }}</p>
                  </div>
                </div>
              </template>
              <p class="item-total-price">
                <span class="tip">总付款</span>
                <span class="symbol">￥</span>
                <span class="value">{{ item.payment }}</span>
              </p>
              <div class="item-operation">
                <p class="more">更多</p>
                <div class="btn-wrapper">
                  <button @click.stop="handleDeleteOrder(item.orderNo)">删除订单</button>
                  <button class="light" v-if="item.status === 1" @click.stop="handleToPay(item)">付款</button>
                </div>
              </div>
            </div>
            <p class="pull-up-text" v-if="isFinish && orderModule.orderList.length > 6">没有更多了</p>
            <p class="pull-up-text" v-if="!isLoading && !isFinish">上拉加载更多</p>
            <p class="pull-up-text" v-if="isLoading && !isFinish">加载中...</p>
          </template>
        </template>
      </ZJScrollView>
    </div>
    <router-view/>
  </div>
</template>

<script setup lang="ts">
import {filterConfigItems, statusList, orderListScrollConfig} from "./config"
import {nextTick, onMounted, ref} from "vue";
import ZJScrollView from "@/components/ZJScrollView/ZJScrollView.vue";
import useOrderModule from "@/store/orderModule";
import {useRoute, useRouter} from "vue-router";
import {Dialog, Toast} from "vant";
import usePayModule from "@/store/payModule";
import {handleToPage} from "@/utils";

const route = useRoute()
const router = useRouter()
const payModule = usePayModule()
const orderModule = useOrderModule()
const orderListScrollRef = ref<InstanceType<typeof ZJScrollView>>()
const form = ref({
  searchCtt: "",
  pageSize: 6,
  pageNum: 1,
  status: 5
})

// 下拉刷新
const pullDownText = ref("")
const isPullingDown = ref(false)
const textItems = {
  "enter": "下拉刷新页面...",
  "leave": "释放刷新页面...",
  "fetching": "加载中...",
  "succeed": "加载完成"
}
// 是否已经全部加载完成
const isFinish = ref(false)
const isLoading = ref(false)
const setupOrderList = async (needToast = false, otherConfig?: any) => {
  let toast = needToast ? Toast.loading("加载中...") : null
  await orderModule.setOrderListAction({
    needNavigate: "/order",
    needToken: true,
    form: form.value,
    ...otherConfig
  })
  if (orderModule.orderList.length >= orderModule.orderListPageInfo.pageTotal) {
    isFinish.value = true
  }
  await nextTick(() => orderListScrollRef.value.bs.refresh())
  toast && toast.clear()
}
// 列表项点击
const handleListItemClick = (orderNo: string) => {
  router.push('/order/detail?payId=' + orderNo)
}
// 付款点击
const handleToPay = async (item: any) => {
  const scriptPage = await payModule.createPayAction({
    paymentType: item.paymentType,
    orderNo: item.orderNo
  })
  if (scriptPage) {
    handleToPage(scriptPage)
  }
}
onMounted(async () => {
  if (route.query.status) { // 如果传递了status就先赋值status
    form.value.status = parseInt(route.query.status as string)
  }
  await setupOrderList(true)
  // 监听加载更多
  orderListScrollRef.value.bs.on("pullingUp", async () => {
    if (isFinish.value) return
    isLoading.value = true
    form.value.pageNum += 1
    await setupOrderList(false, {
      isMoreMode: true
    })
    isLoading.value = false
    orderListScrollRef.value.bs.finishPullUp()
    orderListScrollRef.value.bs.refresh()
  })
  // 监听下拉刷新
  orderListScrollRef.value.bs.on('pullingDown', async () => {
    form.value.pageNum = 1
    pullDownText.value = textItems["fetching"]
    await setupOrderList()
    pullDownText.value = textItems["succeed"]
    orderListScrollRef.value.bs.finishPullDown()
  })
  orderListScrollRef.value.bs.on('enterThreshold', () => {
    pullDownText.value = textItems["enter"]
  })
  orderListScrollRef.value.bs.on('leaveThreshold', () => {
    pullDownText.value = textItems["leave"]
  })
  orderListScrollRef.value.bs.refresh()
})
const resetFormData = () => {
  form.value.pageNum = 1
  form.value.pageSize = 6
  form.value.searchCtt = ""
}
// 全部、待付款等按钮的点击
const handleFilterItemClick = async (key: number) => {
  if (form.value.status !== key) {
    orderListScrollRef.value.bs.scrollTo(0, 0)
    form.value.status = key
    // 初始化其他参数
    resetFormData()
    isFinish.value = false
    orderListScrollRef.value.bs.closePullUp()
    await setupOrderList(true)
    orderListScrollRef.value.bs.refresh()
    orderListScrollRef.value.bs.openPullUp({})
  }
}
// 搜索的处理
const isSearchMode = ref(false)
const handleSearch = async () => {
  // 重新回到第一页
  form.value.pageNum = 1
  isFinish.value = false
  orderListScrollRef.value.bs.scrollTo(0, 0)
  orderListScrollRef.value.bs.closePullUp()
  await setupOrderList(true, {
    isMoreMode: false
  })
  if (form.value.searchCtt) {
    isSearchMode.value = true
    form.value.status = 5
  }
  orderListScrollRef.value.bs.refresh()
  orderListScrollRef.value.bs.openPullUp({})
}
// 删除订单
const handleDeleteOrder = (orderNo: string) => {
  Dialog.confirm({
    title: '提示',
    message:
        '确定要删除这个订单吗？',
  })
      .then(async () => {
        const isSuccess = await orderModule.deleteOrderAction({
          orderNo
        })
        if (isSuccess) {
          // 重新回到第一页
          form.value.pageNum = 1
          Toast.success("删除成功")
          await setupOrderList()
        }
      })
      .catch(() => {
      });
}
</script>

<style scoped lang="less">
@import "src/assets/css/variable";
@import "src/assets/css/mixins";

.my-order {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 889;
  background-color: @theme-grey-color;

  .order-header {
    color: #333;
    font-size: 18px;

    .left-icon {
      font-size: 18px;
    }

    .right-icon {
      font-size: 18px;
    }
  }

  .filter-line {
    background-color: #fff;
    padding: 0 0 10px 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 24px;

    span {
      font-size: 16px;
      transition: all 0.1s ease-in-out;

      &.active {
        color: @orange-color;
        font-size: 18px;
        font-weight: 600;
      }
    }
  }

  .order-list {
    height: calc(100% - 54px - 34px);
    padding: 8px;
    box-sizing: border-box;
    overflow: hidden;

    .list-item {
      margin: 0 0 8px 0;
      padding: 8px;

      .item-title {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;

        .name {
          font-size: 18px;
          font-weight: 600;
        }

        .status {
          color: @orange-color;
        }
      }

      .item-detail {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;

        .detail-img {
          width: 80px;
          height: 80px;

          img {
            width: 100%;
            height: 100%;
            border-radius: 10px;
          }
        }

        .detail-info {
          flex: 1;
          margin: 0 16px;
          overflow: hidden;

          .goods-name {
            font-size: 14px;
            font-weight: 600;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .goods-spec {
            font-size: 14px;
            color: #999;
            .clamp(2);
          }
        }

        .detail-price {
          .price {
            font-weight: 600;
          }

          .count {
            text-align: right;
            color: #999;
          }
        }


      }

      .item-total-price {
        text-align: right;
        margin-bottom: 8px;

        .tip {
          font-size: 14px;
          font-weight: 600;
        }

        .symbol {
          font-size: 12px;
          font-weight: 600;
        }

        .value {
          font-size: 16px;
          font-weight: 600;
        }
      }

      .item-operation {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .more {
          color: #999;
        }

        .btn-wrapper {
          button {
            background: none;
            border: 1px solid #e1e1e1;
            border-radius: 20px;
            padding: 4px 8px;
            font-size: 14px;

            & + button {
              margin-left: 10px;
            }

            &.light {
              border: 1px solid @orange-color;
              color: @orange-color;
              padding: 4px 16px;
            }
          }
        }
      }
    }

    .pull-down-text {
      position: absolute;
      top: -40px;
      left: 50%;
      color: #000;
      z-index: 999;
      transform: translateX(-50%);
    }

    .pull-up-text {
      text-align: center;
      color: #999;
    }
  }

}
</style>
